package com.anzia.study_8.slice;

import com.anzia.study_8.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.TextField;
import ohos.miscservices.pasteboard.PasteData;
import ohos.miscservices.pasteboard.SystemPasteboard;

public class MainAbilitySlice extends AbilitySlice {

	SystemPasteboard systemPasteboard;
	private TextField textField;

	@Override
	public void onStart(Intent intent) {
		super.onStart(intent);
		super.setUIContent(ResourceTable.Layout_ability_main);

		/**
		 * 逻辑：
		 * 1.先获得系统的剪切板
		 * 2.剪切板判空
		 * 3.从文本框中获得数据
		 * 4.将数据添加到pasteDate中
		 * 5.将pasteDate添加到系统剪切板
		 */
		Button copy = (Button) findComponentById(ResourceTable.Id_pasteboard_copy_button);
		copy.setClickedListener(component -> {
			// 拿到系统的剪切板
			systemPasteboard = SystemPasteboard.getSystemPasteboard(MainAbilitySlice.this);
			if (systemPasteboard != null) {
				// PasteData pasteData = PasteData.creatPlainTextData("纯粹的文本数据");
				textField = (TextField) findComponentById(ResourceTable.Id_textfield_pasteboard);
				// 添加黏贴数据
				PasteData pasteData = PasteData.creatPlainTextData(textField.getText());
				// 将黏贴数据添加到系统的剪切板中
				systemPasteboard.setPasteData(pasteData);
			}
		});

		/**
		 * 逻辑：
		 * 1.剪切板判空
		 * 2.从剪切板中获得pasteData
		 * 3.pasteData判空
		 * 4.拿到pasteData的属性
		 * 5.判断pasteData是否是指定属性
		 * 6.从pasteData中获得数据
		 */
		Button paste = (Button) findComponentById(ResourceTable.Id_pasteboard_paste_button);
		paste.setClickedListener(component -> {
			if (systemPasteboard == null)
				return;
			// 要实现从剪贴板里拿数据
			PasteData pasteData = systemPasteboard.getPasteData();
			if (pasteData == null)
				return;
			// 拿到数据属性
			PasteData.DataProperty property = pasteData.getProperty();
			// 判断数据属性
			boolean hasText = property.hasMimeType(PasteData.MIMETYPE_TEXT_PLAIN);
			if (hasText) {
				// 拿文本编辑框
				textField = (TextField) findComponentById(ResourceTable.Id_textfield_pasteboard);
				for (int i = 0; i < pasteData.getRecordCount(); i++) {
					PasteData.Record record = pasteData.getRecordAt(i);
					String mimeType = record.getMimeType();
					if (mimeType.equals(PasteData.MIMETYPE_TEXT_PLAIN)) {
						textField.setText("黏贴后：" + record.getPlainText().toString());
						break;
					}
				}
			}
		});

		// 清除剪切板
		Button clear = (Button) findComponentById(ResourceTable.Id_pasteboard_clear_button);
		clear.setClickedListener(component -> {
			if (systemPasteboard == null)
				return;
			systemPasteboard.clear();
			textField.setText("");
		});

	}

	@Override
	public void onActive() {
		super.onActive();
	}

	@Override
	public void onForeground(Intent intent) {
		super.onForeground(intent);
	}
}
